package middleware

import (
	"myapp/dal/model"
	"myapp/dal/query"
	"net/http"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

// 需要传入数据库实例
func RBACMiddleware(db *gorm.DB, permissionName string) gin.HandlerFunc {
	return func(c *gin.Context) {
		roleIDVal, exists := c.Get("roleID")
		if !exists {
			c.JSON(http.StatusForbidden, gin.H{"error": "角色信息缺失"})
			c.Abort()
			return
		}
		roleID := roleIDVal.(uint)

		var role model.Role
		err := db.Preload("Permissions").First(&role, roleID).Error
		if err != nil {
			c.JSON(http.StatusForbidden, gin.H{"error": "角色不存在"})
			c.Abort()
			return
		}

		perms, _, _ := query.RolePermission.Where(query.RolePermission.RoleID.Eq(int32(roleID))).FindByPage(0, 100)
		for _, perm := range perms {
			perm, _ := query.Permission.Where(query.Permission.ID.Eq(perm.PermissionID)).Take()
			if perm.Name == permissionName {
				c.Next()
				return
			}
		}

		c.JSON(http.StatusForbidden, gin.H{"error": "权限不足"})
		c.Abort()
	}
}
